package com.demo.service.impl;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import com.demo.bean.Asset;
import com.demo.service.AssetReadService;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;

/**
 * @author 李文彬
 * @date 2017年7月13日 下午8:12:55
 * @class
 * @用处 ：
 */
public class AssetReadServiceImpl implements AssetReadService {

	String path2 = System.getProperty("user.dir") + "/src/main/java/com/demo/test/12.xls";

	@Override
	public List<Asset> readAsset(String path) {
		List<Asset> assetList = new ArrayList<Asset>();
		jxl.Workbook readwb = null;
		try {
			// 构建Workbook对象, 只读Workbook对象
			// 直接从本地文件创建Workbook
			InputStream instream = new FileInputStream(path);
			readwb = Workbook.getWorkbook(instream);
			// Sheet的下标是从0开始
			// 获取第一张Sheet表
			Sheet readsheet = readwb.getSheet(0);
			// 获取Sheet表中所包含的总列数
			int rsColumns = readsheet.getColumns();

			// 获取Sheet表中所包含的总行数
			int rsRows = readsheet.getRows();
			int idNum = -1;
			int nameNum = -1;
			int deviceTypeNum = -1;
			int uHighNum = -1;
			for (int j = 0; j < rsColumns; j++) {
				Cell cell = readsheet.getCell(j, 0);
				if ("设备编号".equals(cell.getContents())) {
					idNum = j;
				}
				if ("设备名称".equals(cell.getContents())) {
					nameNum = j;
				}
				if ("设备类型".equals(cell.getContents())) {
					deviceTypeNum = j;
				}
				if ("U高".equals(cell.getContents())) {
					uHighNum = j;
				}
			}
			if (nameNum == -1) {
				nameNum = idNum;
			}
			Cell cell = null;
			// 获取指定单元格的对象引用
			for (int i = 1; i < rsRows; i++) {
				Asset asset = new Asset();
				if (idNum != -1) {
					cell = readsheet.getCell(idNum, i);
					asset.setId(cell.getContents());
				}
				if (nameNum != -1) {
					cell = readsheet.getCell(nameNum, i);
					asset.setName(cell.getContents());
				}
				if (deviceTypeNum != -1) {
					cell = readsheet.getCell(deviceTypeNum, i);
					asset.setDeviceType(cell.getContents());
				}
				if (uHighNum != -1) {
					cell = readsheet.getCell(uHighNum, i);
					asset.setuHigh(cell.getContents());
				}
				if (asset.getDeviceType() != null && asset.getuHigh() != null) {
					assetList.add(asset);
				}
			}
			// if(assetList.size()!=0){
			return assetList;
			// }else{
			// System.out.println("资产数据为空！！！");
			// }

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			readwb.close();
		}
		return null;
	}

	@Override
	public List<Asset> returnAsset() {
		return readAsset(path2);
	}

}
